﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace TriageQueueSystem.InterfacesImplementation
{
    public class HttpHelper : IHttpHelper
    {
        public string HttpGet(string url)
            => this.HttpBase(url, "GET", "");

        /// <summary>
        /// 适用于一个实体传输
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string HttpPost(string url, string param)
            => this.HttpBase(url, "POST", "application/json-patch+json; charset=utf-8", param);

        /// <summary>
        /// 调用该参数请在服务端参数加上<see cref="Microsoft.AspNetCore.Mvc.FromFormAttribute"/>特性
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param">参数结构：{0}={1}&</param>
        /// <returns></returns>
        public string HttpPostForManyParam(string url, string param)
            => this.HttpBase(url, "POST", "application/x-www-form-urlencoded;", param);

        #region Async
        public async Task<string> HttpGetAsync(string url)
            => await this.HttpBaseAsync(url, "GET", "");

        /// <summary>
        /// Json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<string> HttpPostAsync(string url, string param)
            => await this.HttpBaseAsync(url, "POST", "application/json-patch+json; charset=utf-8",param);

        public async Task<string> HttpPostForManyParamAsync(string url, string param)
            => await this.HttpBaseAsync(url, "POST", "application/x-www-form-urlencoded;", param);

        #endregion

        /// <summary>
        /// Http基础方法
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">提交方法 <para>POST/GET</para></param>
        /// <param name="contentType">参数内容类型 
        /// <para>
        ///     1.application/x-www-form-urlencoded  参数格式：{0}={1}&{2}={3}键值对
        ///     2.multipart/form-data  在使用包含文件上传控件的表单时，必须使用该值
        ///     3.application/json  Json字符串
        /// </para>
        /// </param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        private string HttpBase(string url, string method, string contentType, string param = "")
        {
            var webRequest = WebRequest.Create(url) as HttpWebRequest;

            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)";
            webRequest.Method = method;
            webRequest.ContentType = contentType;
            webRequest.Timeout = 15000;
            webRequest.AllowAutoRedirect = false;

            string result = null;
            try
            {
                if (!string.IsNullOrEmpty(param) && (webRequest.ContentType.Contains("json") || webRequest.ContentType.Contains("Json")))
                {
                    StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
                    streamWriter.Write(param);
                    streamWriter.Close();
                }
                else if (!string.IsNullOrEmpty(param) && (webRequest.ContentType.Contains("x-www-form-urlencoded")))
                {
                    var streamWriter = webRequest.GetRequestStream();

                    byte[] postData = Encoding.UTF8.GetBytes(param);
                    webRequest.ContentLength = postData.Length;
                    streamWriter.Write(postData, 0, postData.Length);
                    streamWriter.Close();
                }

                WebResponse response = webRequest.GetResponse();
                bool flag2 = response != null;
                if (flag2)
                {
                    StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    result = streamReader.ReadToEnd();
                    streamReader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
            }
            return result;
        }

        /// <summary>
        /// Http异步基础方法
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">提交方法 <para>POST/GET</para></param>
        /// <param name="contentType">参数内容类型 
        /// <para>
        ///     1.application/x-www-form-urlencoded  参数格式：{0}={1}&{2}={3}键值对
        ///     2.multipart/form-data  在使用包含文件上传控件的表单时，必须使用该值
        ///     3.application/json  Json字符串
        /// </para>
        /// </param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        private async Task<string> HttpBaseAsync(string url, string method, string contentType, string param = "")
        {
            var webRequest = WebRequest.Create(url) as HttpWebRequest;

            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)";
            webRequest.Method = method;
            webRequest.ContentType = contentType;
            webRequest.Timeout = 15000;
            webRequest.AllowAutoRedirect = false;

            string result = null;
            try
            {
                if (!string.IsNullOrEmpty(param) && (webRequest.ContentType.Contains("json") || webRequest.ContentType.Contains("Json")))
                {
                    StreamWriter streamWriter = new StreamWriter(await webRequest.GetRequestStreamAsync());
                    await streamWriter.WriteAsync(param);
                    streamWriter.Close();
                }
                else if (!string.IsNullOrEmpty(param) && (webRequest.ContentType.Contains("x-www-form-urlencoded")))
                {
                    var streamWriter = await webRequest.GetRequestStreamAsync();

                    byte[] postData = Encoding.UTF8.GetBytes(param);
                    webRequest.ContentLength = postData.Length;
                    await streamWriter.WriteAsync(postData, 0, postData.Length);
                    streamWriter.Close();
                }

                WebResponse response = webRequest.GetResponse();
                bool flag2 = response != null;
                if (flag2)
                {
                    StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    result =await streamReader.ReadToEndAsync();
                    streamReader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
            }
            return result;
        }
    }
}
